package cc.siyecao.uid.database.resposity;

import cc.siyecao.uid.core.resposity.AssignerMode;
import cc.siyecao.uid.core.resposity.WorkerNodeResposity;
import cc.siyecao.uid.core.utils.StringUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 配置
 *
 * @author lyt
 */
@Configuration
@Component
public class UidDbConfiguration {

    @Value("${uid-generator.datasource.driver-class-name:}")
    private String driverClassName;
    @Value("${uid-generator.datasource.url:}")
    private String url;
    @Value("${uid-generator.datasource.username:}")
    private String username;
    @Value("${uid-generator.datasource.password:}")
    private String password;

    @Bean
    @Primary
    @ConditionalOnProperty(value = "uid-generator.assigner-mode", havingValue = AssignerMode.DB)
    public WorkerNodeResposity workerNodeResposity(ObjectProvider<DataSource> dataSourcePvd) {
        DataSource dataSource = null;
        if (StringUtils.isNotBlank( this.driverClassName ) &&
                StringUtils.isNotBlank( this.url ) &&
                StringUtils.isNotBlank( this.username ) &&
                StringUtils.isNotBlank( this.password )) {

            HikariDataSource hds = new HikariDataSource();
            hds.setDriverClassName( this.driverClassName );
            hds.setJdbcUrl( this.url );
            hds.setUsername( this.username );
            hds.setPassword( this.password );
            dataSource = hds;
        } else {
            dataSource = dataSourcePvd.getIfAvailable();
        }

        JdbcTemplate jdbcTemplate = new JdbcTemplate( dataSource );
        return new WorkerNodeDatabase( jdbcTemplate );
    }

}
